<!--created by yuyupeng-->
<!--2023/11/30-->
<!-- API接口管理-->
<template>
  <div class="list-card-container">
    <a-card title="API接口管理" class="general-card">
      <!-- 查询表单 -->
      <AdvancedSearch
        ref="searchRef"
        :data-source="searchItemList"
        @change="searchByParams"
      />
      <a-space style="margin-top: 5px; margin-bottom: 5px">
        <a-button type="primary" @click="showAddModal"
          ><icon-plus />新增API接口</a-button
        >
      </a-space>
      <!-- 表格 -->
      <a-table
        v-model:selectedKeys="selectedKeys"
        row-key="id"
        column-resizable
        :columns="tbCols"
        :data="tbData"
        :pagination="pagination"
        :loading="tbLoading"
        :scroll="{ x: '100%', y: 600 }"
        :scrollbar="true"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 插槽-一键复制 -->
        <template #quickCopyToolTip="{ record, column }">
          <quick-copy-tool-tip
            :show-text="record[column['dataIndex']]"
            show-btn
          />
        </template>
        <!-- 插槽：API路径 -->
        <template #apiPath="{ record }">
          <a-tag>/api/infra/form-api/custom/{{ record.apiPath }}</a-tag>
        </template>
        <!-- 插槽：查询类型 -->
        <template #selectType="{ record }">
          <a-tag v-if="record.selectType === 0" color="green"
            >业务实体查询</a-tag
          >
          <a-tag v-if="record.selectType === 1" color="blue">SQL查询</a-tag>
        </template>
        <!-- 插槽-操作 -->
        <template #operation="{ record }">
          <a-space>
            <a-link type="text" @click="showEditModal(record)"> 修改 </a-link>
            <a-link type="text" @click="showPreviewJsonModal(record)">
              数据预览
            </a-link>
            <a-popconfirm
              content="确定删除API接口吗?"
              type="warning"
              @ok="deleteTbData(record.id)"
            >
              <a-link type="text">删除</a-link>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
      <!-- 新增API接口弹窗 -->
      <AdvancedFormModal
        ref="addModalRef"
        width="1400px"
        title="新增API接口"
        :items="addModalConfig"
        :rules="advancedModalRules"
        :mask-closable="false"
        :submit-with-close="false"
        :ok-loading="okBtLoading"
        @change="addModalChange"
        @ok="addModalSubmit"
      >
        <template #selectBusinessEntity>
          <a-space direction="vertical" size="mini">
            <business-entity-select-modal
              :default-checked-business-entity-id-list="
                currentBusinessEntity.length > 0
                  ? [currentBusinessEntity[0].id]
                  : []
              "
              @after-submit="selectedBusinessEntityForAdd"
            />
            <a-tag v-if="currentBusinessEntity.length > 0" color="blue">
              已选择实体：{{ currentBusinessEntity[0].alias }}({{
                currentBusinessEntity[0].name
              }})
            </a-tag>
          </a-space>
        </template>
        <template #otherSlot>
          <div v-if="currentSearchMode === 0">
            <BusinessDetailTable
              ref="businessDetailTableAddRef"
              :show-operation-bt="false"
              :show-row-selection="false"
              @tableNameListChange="businessTableNameListChange"
            />
            <BusinessSearchParamsTable
              v-if="currentBusinessEntity.length > 0"
              ref="businessSearchParamsTableAddRef"
              :table-name-list="currentBusinessTableNameList"
              :data-source-id="currentBusinessEntity[0].dataSourceConfigId"
            />
          </div>
          <div v-else-if="currentSearchMode === 1">
            <a-row style="width: 100%" :gutter="[5, 5]">
              <a-col :span="24">
                <sql-editor ref="sqlEditorAddRef" />
              </a-col>
              <a-col :span="24">
                <sql-search-params-table ref="sqlSearchParamsTableAddRef" />
              </a-col>
            </a-row>
          </div>
        </template>
      </AdvancedFormModal>
      <!-- 修改API接口弹窗 -->
      <AdvancedFormModal
        ref="editModalRef"
        width="1400px"
        title="修改API接口基本信息"
        :items="editModalConfig"
        :rules="advancedModalRules"
        :submit-with-close="false"
        :ok-loading="okBtLoading"
        @change="editModalChange"
        @ok="editModalSubmit"
      >
        <template #selectBusinessEntity>
          <a-space direction="vertical" size="mini">
            <business-entity-select-modal
              :default-checked-business-entity-id-list="
                currentBusinessEntity.length > 0
                  ? [currentBusinessEntity[0].id]
                  : []
              "
              @after-submit="selectedBusinessEntityForEdit"
            />
            <a-tag v-if="currentBusinessEntity.length > 0" color="blue">
              已选择实体：{{ currentBusinessEntity[0].alias }}({{
                currentBusinessEntity[0].name
              }})
            </a-tag>
          </a-space>
        </template>
        <template #otherSlot>
          <div v-if="currentSearchMode === 0">
            <BusinessDetailTable
              ref="businessDetailTableEditRef"
              :show-operation-bt="false"
              :show-row-selection="false"
              @tableNameListChange="businessTableNameListChange"
            />
            <BusinessSearchParamsTable
              v-if="currentBusinessEntity.length > 0"
              ref="businessSearchParamsTableEditRef"
              :table-name-list="currentBusinessTableNameList"
              :data-source-id="currentBusinessEntity[0].dataSourceConfigId"
            />
          </div>
          <div v-else-if="currentSearchMode === 1">
            <a-row style="width: 100%" :gutter="[5, 5]">
              <a-col :span="24">
                <sql-editor
                  v-if="currentAPIDetailInfo"
                  ref="sqlEditorEditRef"
                  :monaco-editor-default-value="
                    currentAPIDetailInfo.extra.defineSql
                  "
                />
              </a-col>
              <a-col :span="24">
                <sql-search-params-table ref="sqlSearchParamsTableEditRef" />
              </a-col>
            </a-row>
          </div>
        </template>
      </AdvancedFormModal>
      <!-- 数据预览弹窗 -->
      <AdvancedFormModal
        ref="previewJsonModalRef"
        width="900px"
        :title="previewJsonModalTitle"
        :items="previewJsonModalConfig"
        :ok-button-props="{ style: { display: 'none' } }"
        :cancel-button-props="{ style: { display: 'none' } }"
      >
        <template #otherSlot>
          <a-space direction="vertical" style="width: 100%">
            <a-row>
              <a-col :span="24">
                <a-input
                  :style="{ width: '100%' }"
                  disabled
                  :placeholder="currentAPIPath"
                >
                  <template #append>
                    <a-button @click="sendPreviewAPI">
                      <template #icon>
                        <icon-send style="color: #ff6c37" />
                      </template>
                      <span style="color: #ff6c37">发送</span>
                    </a-button>
                  </template>
                </a-input>
              </a-col>
            </a-row>
            传参：
            <div style="width: 100%">
              <sql-editor
                ref="searchParamsEditorRef"
                :monaco-editor-default-value="defaultSearchParams"
                monaco-editor-lang="json"
                monaco-editor-height="120px"
              />
            </div>
            返回：
            <div style="width: 100%">
              <sql-editor
                v-if="previewJsonRecord && !previewJsonLoading"
                :monaco-editor-default-value="previewJsonRecord"
                monaco-editor-lang="json"
                monaco-editor-height="400px"
                :read-only="true"
              />
              <a-skeleton v-else animation>
                <!-- 还在加载的时候用骨架屏先占个位子，好看点 -->
                <a-skeleton-line :rows="10" />
              </a-skeleton>
            </div>
          </a-space>
        </template>
      </AdvancedFormModal>
    </a-card>
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import { Notification } from '@arco-design/web-vue';
  import { ref, onMounted, reactive, computed } from 'vue';
  import AdvancedSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AdvancedFormModal from '@/common/components/cac-components/advanced-form-modal/index.vue';
  import QuickCopyToolTip from '@/common/components/cac-components/quickcopy-tooltip/index.vue';
  import { Pagination } from '@/types/global';
  import SqlEditor from '@/views/infrastructure/business-entity/components/sql-editor.vue';
  import BusinessDetailTable from '@/views/infrastructure/business-entity/components/business-detail-table.vue';
  import {
    addAPIRecord,
    deleteAPIRecord,
    executeAPI,
    getAPIDetailInfoById,
    queryAPIRecordListByPage,
    updateAPIRecord,
  } from '@/api/infrastructure/api-management';
  import SqlSearchParamsTable from '@/views/infrastructure/api-management/components/sql-search-params-table.vue';

  import {
    APIAddParams,
    APIDetailInfo,
    APIParams,
    APIRecord,
    ExecuteAPI,
    SQLCondition,
  } from '@/api/infrastructure/model/apiModal';
  import BusinessEntitySelectModal from '@/views/infrastructure/api-management/components/business-entity-select-modal.vue';
  import { BusinessEntityRecord } from '@/api/infrastructure/model/businessEntityModal';
  import { queryDataSourceRecord } from '@/api/infrastructure/data-source-config';
  import { getBusinessEntityColumnRecordById } from '@/api/infrastructure/business-entity';
  import BusinessSearchParamsTable from '@/views/infrastructure/api-management/components/business-search-params-table.vue';

  /**
   * data
   */
  // 表格
  const tbData = ref<APIRecord[]>([]);
  const tbCols = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      fixed: 'left',
      width: 60,
      render: (row: any) => row.rowIndex + 1,
    },
    /* { title: '', dataIndex: 'id', fixed: 'left', ellipsis: true, align: 'center', tooltip: true },
    { title: '查看', fixed: 'left', align: 'center', width: 100, slotName: 'detail' }, */
    { title: 'API名称', dataIndex: 'apiName', width: 150, align: 'center' },
    {
      title: 'API路径',
      dataIndex: 'apiPath',
      width: 200,
      ellipsis: true,
      tooltip: true,
      align: 'center',
      slotName: 'apiPath',
    },
    {
      title: '查询类型',
      dataIndex: 'selectType',
      width: 150,
      ellipsis: true,
      align: 'center',
      slotName: 'selectType',
    },
    {
      title: '创建者',
      dataIndex: 'creator',
      width: 150,
      ellipsis: true,
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      ellipsis: true,
      align: 'center',
    },
    /* { title: '更新者', dataIndex: 'updater', width: 150, ellipsis: true, align: 'center' },
    { title: '更新时间', dataIndex: 'updateTime', width: 150, ellipsis: true, align: 'center' },
    { title: '更新ip', dataIndex: 'updateIp', width: 150, ellipsis: true, align: 'center' },
    { title: '是否删除', dataIndex: 'deleted', width: 150, ellipsis: true, align: 'center' },
    { title: '乐观锁', dataIndex: 'version', width: 150, ellipsis: true, align: 'center' }, */

    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 200,
      slotName: 'operation',
    },
  ];
  const searchRef = ref<any>();
  const addModalRef = ref<any>();
  const editModalRef = ref<any>();
  const sqlEditorAddRef = ref<any>();
  const sqlEditorEditRef = ref<any>();
  const businessDetailTableAddRef = ref<any>();
  const businessSearchParamsTableAddRef = ref<any>();
  const businessDetailTableEditRef = ref<any>();
  const businessSearchParamsTableEditRef = ref<any>();
  const sqlSearchParamsTableAddRef = ref<any>();
  const sqlSearchParamsTableEditRef = ref<any>();
  const previewJsonModalRef = ref<any>();
  const searchParamsEditorRef = ref<any>();
  const previewJsonRecord = ref<any>();
  const defaultSearchParams = JSON.stringify(
    {
      searchParams: {},
      pageNo: 1,
      pageSize: 10,
    },
    null,
    '\t'
  ); // 默认搜索参数， json格式化展示
  const previewJsonLoading = ref<boolean>(false);
  const currentRecord = ref<APIRecord>(); // 当前选中行
  const currentSearchMode = ref<number>(); // 当前选中的查询模式
  const currentBusinessEntity = ref<BusinessEntityRecord[]>([]); // 当前选中的业务实体
  const currentBusinessTableNameList = ref<string[]>([]); // 当前选中的业务实体关联的数据库表名List
  const currentAPIDetailInfo = ref<APIDetailInfo>(); // 当前行对应的API详细信息
  const searchParams = ref<APIRecord>();
  const tbLoading = ref<boolean>(false);
  const okBtLoading = ref<boolean>(false);
  const dataSourceList = ref<any[]>([]); // 数据源配置List
  const dataSourceOptions = ref<any[]>([]); // 数据源下拉框options
  // 勾选框
  const selectedKeys = ref([]);
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 搜索项配置
  const searchItemList = [
    /* { type: 'text', labelText: '', fieldName: 'id'}, */
    { type: 'text', labelText: 'API名称', fieldName: 'apiName' },
    /* { type: 'text', labelText: 'API路径', fieldName: 'apiPath'}, */
    {
      type: 'select',
      labelText: '查询类型',
      fieldName: 'selectType',
      codefield: 'value',
      namefield: 'label',
      options: [
        { label: '业务实体查询', value: 0 },
        { label: 'SQL查询', value: 1 },
      ],
    },
    /* { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除', fieldName: 'deleted'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'}, */
  ];
  // computed
  // 新增弹窗配置项
  const addModalConfig = computed(() => {
    return [
      { span: 6, type: 'text', labelText: 'API名称', fieldName: 'apiName' },
      { span: 6, type: 'text', labelText: 'API路径', fieldName: 'apiPath' },
      {
        span: 6,
        type: 'radioGroup',
        labelText: '查询类型',
        fieldName: 'selectType',
        options: [
          { label: '业务实体查询', value: 0 },
          { label: 'SQL语句查询', value: 1 },
        ],
      },
      {
        span: 6,
        type: 'select',
        labelText: '数据源',
        fieldName: 'dataSourceConfigId',
        codefield: 'value',
        namefield: 'label',
        options: dataSourceOptions.value,
        visible: currentSearchMode.value === 1,
      },
      {
        span: 6,
        type: 'other',
        labelText: '业务实体',
        fieldName: 'selectBusinessEntity',
        visible: currentSearchMode.value === 0,
      },
      {
        span: 24,
        type: 'other',
        labelText: currentSearchMode.value === 1 ? 'SQL语句' : '业务实体字段',
        fieldName: 'otherSlot',
      },
    ];
  });
  // 修改弹窗配置项
  const editModalConfig = computed(() => {
    return [
      {
        span: 24,
        type: 'text',
        labelText: 'id',
        fieldName: 'id',
        visible: false,
      },
      { span: 6, type: 'text', labelText: 'API名称', fieldName: 'apiName' },
      { span: 6, type: 'text', labelText: 'API路径', fieldName: 'apiPath' },
      {
        span: 6,
        type: 'radioGroup',
        labelText: '查询类型',
        fieldName: 'selectType',
        disabled: true,
        options: [
          { label: '业务实体查询', value: 0 },
          { label: 'SQL语句查询', value: 1 },
        ],
      },
      {
        span: 6,
        type: 'select',
        labelText: '数据源',
        fieldName: 'dataSourceConfigId',
        codefield: 'value',
        namefield: 'label',
        options: dataSourceOptions.value,
        visible: currentSearchMode.value === 1,
      },
      {
        span: 6,
        type: 'other',
        labelText: '业务实体',
        fieldName: 'selectBusinessEntity',
        visible: currentSearchMode.value === 0,
      },
      {
        span: 24,
        type: 'other',
        labelText: currentSearchMode.value === 1 ? 'SQL语句' : '业务实体字段',
        fieldName: 'otherSlot',
      },
    ];
  });
  // 数据预览弹窗配置项
  const previewJsonModalConfig = computed(() => {
    return [{ span: 24, type: 'other', labelText: '', fieldName: 'otherSlot' }];
  });
  // 数据预览弹窗Title
  const previewJsonModalTitle = computed(() => {
    return `/api/infra/form-api/custom/${currentRecord.value?.apiPath} 接口的数据预览`;
  });
  // 当前API的path
  const currentAPIPath = computed(() => {
    return `/api/infra/form-api/custom/${currentRecord.value?.apiPath}`;
  });
  // 弹窗表单项校验配置
  const advancedModalRules = computed(() => {
    return {
      apiName: [{ required: true, message: '请输入API名称' }],
      apiPath: [{ required: true, message: '请输入API路径' }],
      selectType: [{ required: true, message: '请选择查询类型' }],
      dataSourceConfigId: [
        { required: currentSearchMode.value === 1, message: '请选择数据源' },
      ],
    };
  });
  /**
   * func
   */
  /**
   * @method
   * @description 获取表格数据
   */
  const getTbDataByPage = async () => {
    const params: APIParams = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...searchParams.value,
    };
    tbLoading.value = true;
    selectedKeys.value = [];
    try {
      const { data } = await queryAPIRecordListByPage(params);
      tbData.value = data.list;
      pagination.total = Number(data.total); // 用Number函数转一下，否则f12控制台会有警告，很不好看
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      tbLoading.value = false;
    }
  };
  /**
   * @method
   * @description 按条件搜索
   */
  const searchByParams = (reqdata: any = {}) => {
    searchParams.value = reqdata;
    getTbDataByPage();
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 删除API接口信息
   */
  const deleteTbData = async (id: string) => {
    try {
      const res = (await deleteAPIRecord(id)) as any;
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 获取数据源配置List
   */
  const listDataSource = async () => {
    const { data } = await queryDataSourceRecord();
    dataSourceList.value = data;
    dataSourceOptions.value = [];
    dataSourceList.value.forEach((elem) => {
      dataSourceOptions.value.push({ label: elem.name, value: elem.id });
    });
  };
  /**
   * @description 打开新增弹窗
   */
  const showAddModal = async () => {
    currentSearchMode.value = 1;
    currentBusinessEntity.value = [];
    addModalRef.value.open({
      selectType: 1,
      dataSourceConfigId: dataSourceOptions.value[0].value,
    });
  };
  /**
   * @method
   * @description 新增弹窗提交
   */
  const addModalSubmit = async (reqdata: any) => {
    try {
      okBtLoading.value = true;
      let apiAddParams: APIAddParams = {
        extra: '',
      };
      if (reqdata.selectType === 0) {
        // 业务实体查询
        if (currentBusinessEntity.value.length === 0) {
          Notification.warning({
            content: '请选择业务实体！',
          });
          return;
        }
        const businessSearchParamsTableDataList = JSON.parse(
          JSON.stringify(businessSearchParamsTableAddRef.value.getFieldList())
        );
        let flag = false;
        businessSearchParamsTableDataList.forEach((elem: any) => {
          Object.keys(elem).forEach((item) => {
            if (item === 'fieldName' || item === 'jsonName') {
              if (elem[item].length === 0) {
                flag = true; // 发现有接口查询条件字段为空或数据库表字段为空，不允许提交
              }
            }
          });
        });
        if (flag) {
          Notification.warning({
            content: '必填字段不能为空！',
          });
          return;
        }
        const sqlConditions: SQLCondition[] = [];
        businessSearchParamsTableDataList.forEach((elem: any) => {
          sqlConditions.push({
            fieldName: elem.fieldName,
            defaultCondi: elem.defaultCondi,
            jsonName: elem.jsonName,
            mutable: elem.mutable,
            selectType: elem.selectType,
            tableName: elem.tableName,
          });
        });
        apiAddParams = {
          ...reqdata,
          extra: {
            entityId: currentBusinessEntity.value[0].id,
            sqlConditions,
          },
        };
      } else if (reqdata.selectType === 1) {
        // SQL查询
        const sqlSearchParamsTableDataList = JSON.parse(
          JSON.stringify(sqlSearchParamsTableAddRef.value.getFieldList())
        );
        let flag = false;
        sqlSearchParamsTableDataList.forEach((elem: any) => {
          Object.keys(elem).forEach((item) => {
            if (item === 'fieldName' || item === 'jsonName') {
              if (elem[item].length === 0) {
                flag = true; // 发现有接口查询条件字段为空或数据库表字段为空，不允许提交
              }
            }
          });
        });
        if (flag) {
          Notification.warning({
            content: '必填字段不能为空！',
          });
        } else if (sqlEditorAddRef.value.getEditorValue().length === 0) {
          Notification.warning({
            content: 'SQL语句不能为空！',
          });
        } else {
          const sqlConditions: SQLCondition[] = [];
          sqlSearchParamsTableDataList.forEach((elem: any) => {
            sqlConditions.push({
              fieldName: elem.fieldName,
              defaultCondi: elem.defaultCondi,
              jsonName: elem.jsonName,
              mutable: elem.mutable,
              selectType: elem.selectType,
              tableName: elem.tableName,
            });
          });
          apiAddParams = {
            ...reqdata,
            extra: {
              dataSourceConfigId: reqdata.dataSourceConfigId,
              defineSql: sqlEditorAddRef.value.getEditorValue(),
              sqlConditions,
            },
          };
          delete apiAddParams.dataSourceConfigId;
        }
      }
      const res = (await addAPIRecord(apiAddParams)) as any;
      if (res.code === 200) {
        Notification.success({
          content: '保存成功！',
        });
        addModalRef.value.close();
      } else {
        Notification.error({
          title: '保存失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      okBtLoading.value = false;
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 新增弹窗表单数据变化触发
   * @param name
   * @param value
   */
  const addModalChange = (name: string, value: any) => {
    if (name === 'selectType') {
      // 如果是查询类型变化了，则更新currentSearchMode
      currentSearchMode.value = value;
    }
  };
  /**
   * @description 修改弹窗表单数据变化触发
   * @param name
   * @param value
   */
  const editModalChange = (name: string, value: any) => {
    if (name === 'selectType') {
      // 如果是查询类型变化了，则更新currentSearchMode
      currentSearchMode.value = value;
    }
  };
  /**
   * @description 打开修改API接口弹窗
   */
  const showEditModal = async (record: APIRecord) => {
    const { data } = await getAPIDetailInfoById(record.id as string);
    currentAPIDetailInfo.value = data;
    currentSearchMode.value = data.selectType;
    if (data.selectType === 0) {
      // 业务实体查询
      currentBusinessEntity.value = [
        {
          id: data.extra.entityId,
          alias: data.extra.alias, // 实体名称
          name: data.extra.name, // 实体编码
          dataSourceConfigId: data.extra.dataSourceConfigId, // 数据源id
        },
      ];
    } else if (data.selectType === 1) {
      // SQL查询
      record.dataSourceConfigId = data.extra.dataSourceConfigId;
    }
    editModalRef.value.open(record);
    if (data.selectType === 0) {
      // 业务实体查询
      const dataSourceConfigName = dataSourceList.value.filter(
        (e) => e.id === data.extra.dataSourceConfigId
      )[0].name;
      data.extra.entityAttrs.forEach((item: any) => {
        item.dataSourceName = dataSourceConfigName;
        item.disabled = true;
      });
      setTimeout(() => {
        businessDetailTableEditRef.value.clearFieldList();
        businessDetailTableEditRef.value.addTbDataBatch(data.extra.entityAttrs);
        setTimeout(() => {
          // 这里必须再来一个setTimeout，因为要等前面的addTbDataBatch操作完才会触发tableNameChange，否则init方法不起作用
          businessSearchParamsTableEditRef.value.init(); // 实体查询条件重置一下
          businessSearchParamsTableEditRef.value.addTbDataBatch(
            data.extra.sqlConditions
          );
        }, 500);
      }, 500);
    } else if (data.selectType === 1) {
      // SQL查询
      setTimeout(() => {
        sqlSearchParamsTableEditRef.value.clearFieldList();
        sqlSearchParamsTableEditRef.value.addTbDataBatch(
          data.extra.sqlConditions
        );
      }, 500);
    }
  };
  /**
   * @method
   * @description 修改弹窗提交
   */
  const editModalSubmit = async (reqdata: APIRecord) => {
    try {
      okBtLoading.value = true;
      let apiEditParams: APIAddParams = {
        extra: '',
      };
      if (reqdata.selectType === 0) {
        // 业务实体查询
        const businessSearchParamsTableDataList = JSON.parse(
          JSON.stringify(businessSearchParamsTableEditRef.value.getFieldList())
        );
        let flag = false;
        businessSearchParamsTableDataList.forEach((elem: any) => {
          Object.keys(elem).forEach((item) => {
            if (item === 'fieldName' || item === 'jsonName') {
              if (elem[item].length === 0) {
                flag = true; // 发现有接口查询条件字段为空或数据库表字段为空，不允许提交
              }
            }
          });
        });
        if (flag) {
          Notification.warning({
            content: '必填字段不能为空！',
          });
          return;
        }
        const sqlConditions: SQLCondition[] = [];
        businessSearchParamsTableDataList.forEach((elem: any) => {
          sqlConditions.push({
            fieldName: elem.fieldName,
            defaultCondi: elem.defaultCondi,
            jsonName: elem.jsonName,
            mutable: elem.mutable,
            selectType: elem.selectType,
            tableName: elem.tableName,
          });
        });
        apiEditParams = {
          ...reqdata,
          extra: {
            entityId: currentBusinessEntity.value[0].id,
            sqlConditions,
          },
        } as APIAddParams;
      } else if (reqdata.selectType === 1) {
        // SQL查询
        const sqlSearchParamsTableDataList = JSON.parse(
          JSON.stringify(sqlSearchParamsTableEditRef.value.getFieldList())
        );
        let flag = false;
        sqlSearchParamsTableDataList.forEach((elem: any) => {
          Object.keys(elem).forEach((item) => {
            if (item === 'fieldName') {
              if (elem[item].length === 0) {
                flag = true; // 发现有接口查询条件字段为空或数据库表字段为空，不允许提交
              }
            }
          });
        });
        if (flag) {
          Notification.warning({
            content: '必填字段不能为空！',
          });
        } else if (sqlEditorEditRef.value.getEditorValue().length === 0) {
          Notification.warning({
            content: 'SQL语句不能为空！',
          });
        } else {
          const sqlConditions: SQLCondition[] = [];
          sqlSearchParamsTableDataList.forEach((elem: any) => {
            sqlConditions.push({
              fieldName: elem.fieldName,
              defaultCondi: elem.defaultCondi,
              jsonName: elem.jsonName,
              mutable: elem.mutable,
              selectType: elem.selectType,
              tableName: elem.tableName,
            });
          });
          apiEditParams = {
            ...reqdata,
            extra: {
              dataSourceConfigId: reqdata.dataSourceConfigId,
              defineSql: sqlEditorEditRef.value.getEditorValue(),
              sqlConditions,
            },
          };
          delete apiEditParams.dataSourceConfigId;
        }
      }
      const res = (await updateAPIRecord(apiEditParams)) as any;
      if (res.code === 200) {
        Notification.success({
          content: '修改成功！',
        });
        editModalRef.value.close();
      } else {
        Notification.error({
          title: '修改失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      okBtLoading.value = false;
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 新增API接口对话框选择业务实体后触发
   * @param businessEntity
   */
  const selectedBusinessEntityForAdd = async (businessEntity: any) => {
    currentBusinessEntity.value = businessEntity;
    const dataSourceConfigName = dataSourceList.value.filter(
      (e) => e.id === businessEntity[0].dataSourceConfigId
    )[0].name;
    const { data } = await getBusinessEntityColumnRecordById(
      // 获取实体字段
      businessEntity[0].id
    );
    data.forEach((item: any) => {
      item.dataSourceName = dataSourceConfigName;
      item.disabled = true;
    });
    setTimeout(() => {
      businessDetailTableAddRef.value.clearFieldList(); // 先清空一下原有的实体字段信息
      businessDetailTableAddRef.value.addTbDataBatch(data);
      setTimeout(() => {
        // 这里必须再来一个setTimeout，因为要等前面的addTbDataBatch操作完才会触发tableNameChange，否则init方法不起作用
        businessSearchParamsTableAddRef.value.init(); // 实体查询条件重置一下
      }, 500);
    }, 500);
  };
  /**
   * @description 修改API接口对话框选择业务实体后触发
   * @param businessEntity
   */
  const selectedBusinessEntityForEdit = async (businessEntity: any) => {
    currentBusinessEntity.value = businessEntity;
    const dataSourceConfigName = dataSourceList.value.filter(
      (e) => e.id === businessEntity[0].dataSourceConfigId
    )[0].name;
    const { data } = await getBusinessEntityColumnRecordById(
      // 获取实体字段
      businessEntity[0].id
    );
    data.forEach((item: any) => {
      item.dataSourceName = dataSourceConfigName;
    });
    setTimeout(() => {
      businessDetailTableEditRef.value.clearFieldList(); // 先清空一下原有的实体字段信息
      businessDetailTableEditRef.value.addTbDataBatch(data);
      setTimeout(() => {
        // 这里必须再来一个setTimeout，因为要等前面的addTbDataBatch操作完才会触发tableNameChange，否则init方法不起作用
        businessSearchParamsTableEditRef.value.init(); // 实体查询条件重置一下
      }, 500);
    }, 500);
  };
  /**
   * @description 执行API
   */
  const sendPreviewAPI = async () => {
    try {
      const req = JSON.parse(
        searchParamsEditorRef.value.getEditorValue()
      ) as ExecuteAPI;
      previewJsonLoading.value = true;
      const result = await executeAPI(
        currentRecord.value?.apiPath as string,
        req
      );
      previewJsonLoading.value = false;
      previewJsonRecord.value = JSON.stringify(result, null, '\t'); // json格式化展示
    } catch (error) {
      const errorMessage = {
        errorInfo: (error as any).toString(),
      };
      previewJsonRecord.value = JSON.stringify(errorMessage, null, '\t'); // json格式化展示
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      previewJsonLoading.value = false;
    }
  };
  /**
   * @description 数据预览
   * @param record
   */
  const showPreviewJsonModal = async (record: APIRecord) => {
    try {
      previewJsonModalRef.value.open();
      currentRecord.value = record;
      const req = JSON.parse(defaultSearchParams) as ExecuteAPI; // 打开数据预览窗口后默认先查一遍
      previewJsonLoading.value = true;
      const result = await executeAPI(record.apiPath as string, req);
      previewJsonLoading.value = false;
      previewJsonRecord.value = JSON.stringify(result, null, '\t'); // json格式化展示
    } catch (error) {
      const errorMessage = {
        errorInfo: (error as any).toString(),
      };
      previewJsonRecord.value = JSON.stringify(errorMessage, null, '\t'); // json格式化展示
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      previewJsonLoading.value = false;
    }
  };
  /**
   * @description 当前选中的实体关联的表名
   * @param tableNameList
   */
  const businessTableNameListChange = (tableNameList: string[]) => {
    currentBusinessTableNameList.value = tableNameList;
  };
  /**
   * onMounted
   */
  onMounted(() => {
    getTbDataByPage();
    listDataSource();
  });
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    // background-color: var(--color-bg-1);
    border-radius: var(--border-radius-default);
  }
</style>
